#include <bits/stdc++.h>

using namespace std;
class Solution
{
public:
    bool checkArrive(const pair<int, int> &start, const pair<int, int> &dest)
    {
        int x_len = abs(dest.first - start.first);
        int y_len = abs(dest.second - start.second);
        if (x_len == 2 && y_len == 1 || x_len == 1 && y_len == 2)
        {
            return true;
        }
        return false;
    }

    bool checkValidGrid(vector<vector<int>> &grid)
    {
        vector<pair<int, int>> dest(grid.size() * grid.size());
        pair<int, int> start;
        for (int i = 0; i < grid.size(); ++i)
        {
            for (int j = 0; j < grid[i].size(); ++i)
            {
                int count = grid[i][j];
                dest[count] = {i, j};
            }
        }

        if (dest[0].first != 0 || dest[0].second != 0)
        {
            return false;
        }

        for (int i = 0; i < dest.size() - 1; ++i)
        {
            if (!checkArrive(dest[i], dest[i + 1]))
            {
                return false;
            }
        }
        return true;
    }
};